<template>
  <el-dialog v-model="visiable" align-center title="微信账号绑定" width="650px" class="dialog"  @closed="onClosed">
    <div class="qrcode-content" v-loading="isLoading">
      <div v-if="isShowQrCode" class="qrcode-login">
        <!-- 二维码 -->
        <img v-if="qrCode.url" :src="qrCode.url">
        <!-- 二维码过期 -->
        <div v-if="isExpire && !isScan" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
          <el-result icon="error" title="二维码已过期,请重新获取">
            <template #extra>
              <el-button icon="RefreshRight" @click="onShowQrCode">刷新二维码</el-button>
            </template>
          </el-result>
        </div>
        <!-- 二维码已扫描且 绑定成功或用户用未绑定账号的微信扫码,但账号已绑定了其他微信 -->
        <div v-if="isScan && isSuccess" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
          <el-result icon="success" :title="bindSuccessText"></el-result>
        </div>
         <!-- 当用户用未绑定账号的微信扫码,但账号已绑定了其他微信时 -->
        <div v-if="isScan && isUserBindWx" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
          <el-result icon="warning" title="该账号已绑定其他微信">
            <template #extra><el-button type="warning"  @click="onChangeWx">更换为该微信</el-button></template>
          </el-result>
        </div>
        <!-- 二维码已扫描且扫描的微信已绑定其他账号 -->
        <div v-if="isScan && isWxBindUser" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
          <el-result icon="warning" title="该微信已绑定其他账号" sub-title="请使用该账号对应微信或未绑定账号的微信扫码"></el-result>
        </div>
        <!-- 文字提示 -->
        <span v-if="!isExpire && !isScan && !isLoading" class="qrcode-text">请使用微信扫一扫~</span>
        <span v-if="!isExpire && !isScan && !isLoading" class="qrcode-text">二维码将在{{ qrCode.expireSeconds }}秒后过期</span>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAPI } from '../../request/api';
import { useUserStore } from '../../store/user';
import { APIData, IQrCodeParams, IScanQrCodeRes } from '../../type';
import { ElMessage } from 'element-plus';

let timeCountdownTimer = -1;
let cycleLoginTimer = -1;
let qrCodeUserId = '';
let qrCodeTimeStamp = '';
let cycleQueryToBindRes = {} as IScanQrCodeRes;
const api = useAPI();
const userStore = useUserStore();
const isShowQrCode = ref<boolean>(false);
const isExpire = ref<boolean>(false);
const isScan = ref<boolean>(false);
const isUserBindWx = ref<boolean>(false);
const isWxBindUser = ref<boolean>(false);
const isSuccess = ref<boolean>(false);
const isLoading = ref<boolean>(false);
const bindSuccessText = ref('');
const visiable = ref(false);
const qrCode = ref({ url: '',expireSeconds: 0,width: 0,height: 0})

const open = () => {
  visiable.value = true;
  onShowQrCode();
}

const onShowQrCode = async () => {
  isLoading.value = true;
  qrCodeTimeStamp =  String(new Date().getTime());
  if(userStore.role == 'student') qrCodeUserId = userStore.userInfo.studentId;
  else if(userStore.role == 'teacher') qrCodeUserId = userStore.userInfo.workId;
  else ElMessage.error('系统角色信息错误');
  const res: APIData = await api.getQrCode({ qrCodeParams: `${qrCodeUserId}${qrCodeTimeStamp}` });
  if (res.code === 200) {
    qrCode.value = {
      url: `data:image/jpeg;base64,${res.data.qrCodeBase64}`,
      expireSeconds: res.data.expireSeconds,
      width: res.data.width,
      height: res.data.height
    }
    isShowQrCode.value = true;
    isLoading.value = false;
    isExpire.value = false;
    isScan.value = false;

    timeCountdown();
    cycleQueryToBind();
  }
  else ElMessage.error('网络波动，请重新生成登陆二维码');

  //测试----
  // qrCode.value = {
  //     url: '/src/assets/image/testCode.png',
  //     expireSeconds: 2,
  //     width: 300,
  //     height: 300
  //   }
  //   isShowQrCode.value = true;
  //   isLoading.value = false;
  //   isExpire.value = false;
  //   isScan.value = false;
  //   timeCountdown();
}

const timeCountdown = async () => {
  timeCountdownTimer = setInterval(() => {
    if (qrCode.value.expireSeconds > 1) qrCode.value.expireSeconds--;
    else {isUserBindWx
      if(timeCountdownTimer != -1) clearInterval(timeCountdownTimer);
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
      isExpire.value = true; 
      //也要结束轮询计时器
    }
  }, 1000);
}

const cycleQueryToBind = () => {
  cycleLoginTimer = setInterval(async () => {
    const res:APIData = await api.bindWeixin.bindWeiXinByQrCode({ userId: qrCodeUserId,timeStamp: qrCodeTimeStamp });
    if (res.code == 200 && res.data) {
      isScan.value = true;
      cycleQueryToBindRes = res.data;
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
      if(res.message == '该账号已绑定其他微信') isUserBindWx.value = true; 
      if(res.message == '绑定成功' || res.message == '该账号已绑定微信') {
        bindSuccessText.value = res.message as string;
        isSuccess.value = true;
      }
    }else if(res.code == 200 && res.message?.indexOf('该微信已绑定其他账号') != -1) {
      isScan.value = true;
      isWxBindUser.value = true;
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
    }
  }, 2000);
}

const onChangeWx = async () => {
  if(!cycleQueryToBindRes.openId || qrCodeUserId == '') {
    ElMessage.error('系统更换绑定微信信息丢失');
    return;
  }
  const res:APIData = await api.bindWeixin.updateWxBind({ userId: qrCodeUserId,openId: cycleQueryToBindRes.openId });
  if (res.code == 200 && res.data) {
    isSuccess.value = true;
    isUserBindWx.value = false;
    bindSuccessText.value = '绑定成功';
  }else ElMessage.error(res.message);
}

const onClosed = () => {
  isShowQrCode.value = false;
  isExpire.value = false;
  isScan.value = false;
  isWxBindUser.value = false;
  isUserBindWx.value = false;
  isSuccess.value = false;
  isLoading.value = false;
  if(timeCountdownTimer != -1) clearInterval(timeCountdownTimer);
  if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.qrcode-content {
  min-height: 350px;
}
.qrcode-login {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .qrcode-text {
    margin-top: 8px;
    // border: 1px solid green;
  }
  .qrcode-expire-mask {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    background-color: #fffffff5;
    // border: 1px solid #95beec;
  }
}

</style>